package nl.Viewer.Dialogs.DatasetSelection;

import java.awt.datatransfer.Transferable;
import java.util.Enumeration;

import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

/**
 * This class adds the drag-and-drop functionality to the tree with modalities and visualizations 
 * 
 * @author Jeroen Verschuur
 *
 */

public class DatasetTreeTransferHandler extends TransferHandler {
	private static final long serialVersionUID = -1;	
	public DatasetTreeTransferHandler() {
		super();
	}
	
	public int getSourceActions(JComponent comp) {
        return LINK;
    }

	public Transferable createTransferable(JComponent comp) {
    	JTree source = (JTree)comp;
    	
    	// set up an object to be transfered while dropping
    	DatasetSelectionTransferObject tObject = new DatasetSelectionTransferObject();
    	
    	TreePath []paths = source.getSelectionPaths();
    	if(paths == null) return null;
    	for(int i = 0; i < paths.length; i++) {
    		DefaultMutableTreeNode node = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
    		
    		// go through the dragged node and all its children (the first element of the enumeration is
    		// the selected element itself)
			Enumeration<?> e = node.preorderEnumeration();
			
			while(e.hasMoreElements()) {
				DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)e.nextElement();
				if(childNode.getUserObject() instanceof VisualizationItemPanel) {
				   
//				   System.out.println("vis: "+((VisualizationItemPanel)childNode.getUserObject()).visualization);
//				   System.out.println("modality: "+((ModalityItemPanel)((DefaultMutableTreeNode)childNode.getParent()).getUserObject()).modality);
				   
					tObject.addObject(
					      ((VisualizationItemPanel)childNode.getUserObject()).visualization, 
					      ((ModalityItemPanel)((DefaultMutableTreeNode)childNode.getParent()).getUserObject()).modality);
				} // otherwise: a node in the tree that we don't need
			}
    	}
    	return tObject;
    }
    
    public void exportDone(JComponent comp, Transferable trans, int action) {
        // do nothing with the list
    }

}

